﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace Tools.Utilities
{
    public static class XMLUtils
    {
        public static T Deserialize<T>(string xml) where T : class
        {
            using (var stringReader = new StringReader(xml))
            {
                var ser = new XmlSerializer(typeof(T));
                var obj = (T)ser.Deserialize(stringReader);
                return obj;
            }
        }

        public static string Serialize<T>(T obj) where T : class
        {
            using (var stream = new MemoryStream())
            {
                var serializer = new XmlSerializer(typeof(T));
                try
                {
                    serializer.Serialize(stream, obj);
                }
                catch (Exception)
                {
                    return string.Empty;
                }

                stream.Position = 0;
                return new StreamReader(stream).ReadToEnd();
            }
        }
    }
}
